//Pirate Ship Wars
//By EmpV, Metroid48, and Termy58
//Remade for Gmod 10 by Metroid48, and Termy58

Msg("\nLoading PirateShip Wars server files\n")

include("shared.lua")
//include("sv_commands.lua")

AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")

//Var define
ships = false
PirateData = {}
n1=35
n2=35
canSpawn = false
exploded = {}

//Sets data for players and disables drag (hopefully)
for _,k in pairs(player.GetAll()) do
	PirateData[k:EntIndex()] = {}
	PirateData[k:EntIndex()].Heal = false
	PirateData[k:EntIndex()].LastPos=nil
	PirateData[k:EntIndex()].KD = 0
	PirateData[k:EntIndex()].LastSpawn = nil
	PirateData[k:EntIndex()].parented = false
//	PirateData[k:EntIndex()].driving = false
	k:GetPhysicsObject():EnableDrag(false)
end

////
//Menus
////

function GM:ShowHelp(pl)
	umsg.Start("HelpMenu", pl)
	umsg.Short( 7 )
	umsg.End()
end

function GM:ShowTeam(pl)
	umsg.Start("TeamMenu", pl)
	umsg.Short( 8 )
	umsg.End()
end

function GM:ShowSpare1( ply ) //F3

end

function GM:ShowSpare2( ply ) //F4

end

////
//General player console commands
////

function teamSwitch( pl, command, args )
Msg("Start Switch")
	local rr= team.NumPlayers(TEAM_RED)
	local bb= team.NumPlayers(TEAM_BLUE)
	if args[1]==TEAM_RED then
		if rr+1<=bb+1 then
			pl:SetTeam(TEAM_RED)
		end
	elseif args[1]==TEAM_BLUE then
		if bb+1<=rr+1 then
			pl:SetTeam(TEAM_BLUE)
		end
	end
end
concommand.Add("psw_switch", teamSwitch)

////
//Lag Reduction (I hope...)
////
/*function GM:Move(pl, movedata)
	if PirateData[pl:EntIndex()].parented then
		pl:SetParent()
		PirateData[pl:EntIndex()].parented = false
	end
end

function GM:FinishMove(pl, movedata)
	if ships then
		if !PirateData[pl:EntIndex()].parented then
			if pl:Team()==TEAM_RED then
				pl:SetParent(ents.FindByName("ship1keel")[1])
				Msg("SettingParent\n")
			elseif pl:Team()==TEAM_BLUE then
				pl:SetParent(ents.FindByName("ship2keel")[1])
				Msg("SettingParent\n")
			end
		end
	end
end*/

////
//Main function hooks
////

//Spawn Function
function GM:PlayerSpawn( pl )
	if canSpawn then
//		pl:Spectate(0)
		pl:UnSpectate()
		local bb=team.NumPlayers(TEAM_BLUE)
		local rr=team.NumPlayers(TEAM_RED)

		if pl:Team()== TEAM_SPECTATE then
			if bb==rr then
				pl:SetTeam(TEAM_RED)
			elseif bb>rr then
				pl:SetTeam(TEAM_RED)
			else
				pl:SetTeam(TEAM_BLUE)
			end
		pl:Spectate(0)
		pl:UnSpectate()
		end
		if bb>rr+1 then
			pl:SetTeam(TEAM_RED)
		elseif rr>bb+1 then
			pl:SetTeam(TEAM_BLUE)
		end
		GAMEMODE:PlayerLoadout( pl )
		GAMEMODE:PlayerSetModel( pl )
		GAMEMODE:SetPlayerSpeed( pl, 250, 500 )
	else
		pl:SetTeam(TEAM_SPECTATE)
		pl:Spectate(5)
		if PirateData[pl:EntIndex()].LastPos then
			pl:SetPos(PirateData[pl:EntIndex()].LastPos)
			PirateData[pl:EntIndex()].LastPos = nil
		end
	end
/*	if pl:IsAdmin() then
		pl:GodDisable()
		if string.find(pl:GetName(), "[godmode]") then
			pl:GodEnable()
		end
	end*/
	pl:GodDisable()
end

function enableSpawning()
	canSpawn = true
	for k,v in pairs(player.GetAll()) do
		v:ConCommand("kill")
//		v:Respawn()
	end
end
timer.Simple(5, enableSpawning)

/*function GM:PlayerUse(pl, ents)
	local name = ents:GetName()
	if name=="ship2drivebutton" then
		if pl:Team()==TEAM_BLUE then
			PirateData[pl:EntIndex()].driving=!PirateData[pl:EntIndex()].driving
			shipfunctions(pl, PirateData[pl:EntIndex()].driving, ents)
			return true
		else
			pl:PrintMessage(HUD_PRINTTALK, "Don't jack their ship!")
			return false
		end
	elseif name=="ship1drivebutton" then
		if pl:Team()==TEAM_RED then
			PirateData[pl:EntIndex()].driving=!PirateData[pl:EntIndex()].driving
			shipfunctions(pl, PirateData[pl:EntIndex()].driving, ents)
			return true
		else
			pl:PrintMessage(HUD_PRINTTALK, "Don't jack their ship!")
			return false
		end
	end
end*/

//Returns correct spawn point for team
function GM:PlayerSelectSpawn( pl )
//Defines table of spawn points
//local blueSpawns = 
//local redSpawns = 
	local tempTable = nil
	if pl:Team()==TEAM_BLUE then
		tempTable = ents.FindByClass("info_player_deathmatch")
	else
		tempTable = ents.FindByClass("info_player_start")
	end

	local cnt=#tempTable
	local nearest = nil

	if cnt==0 then return pl end
	local chosen = false
	for k,v in pairs(tempTable) do
		nearest = ents.FindInSphere(v:GetPos(), 10)
		if v:IsValid() && v:IsInWorld() then
			local blk = false
			local newTarget = v
//			local i = 0
			for i,o in pairs(nearest) do
				if o:GetClass()=="trigger_teleport" then
					newTarget = ents.FindByName(o:GetKeyValues().target)[1]
//					i=i+1
//					Msg("Adding newtarget of "..tostring(o:GetKeyValues().target).."\n")
				end
			end
//			if i==0 then
//				newTarget=v
//				Msg("Resetting newtarget.\n")
//			end
			for o,l in pairs(ents.FindInSphere(newTarget:GetPos(),150)) do
				if l:IsValid() && l:IsPlayer() then
//					Msg("Spawn blocked\n")
					blk = true
				end
			end
			if !blk then
				if !PirateData[pl:EntIndex()].LastSpawn then
					chosen = true
					PirateData[pl:EntIndex()].LastSpawn=v
					return v
				elseif PirateData[pl:EntIndex()].LastSpawn ~= v then
						chosen = true
						PirateData[pl:EntIndex()].LastSpawn=v
						return v
				end
			end
		end
	end
	if !chosen then
		return pl
	end
end

function GM:PlayerInitialSpawn( pl )
//	GM:ShowHelp(pl)
	PirateData[pl:EntIndex()] = {}
	PirateData[pl:EntIndex()].Heal = false
	PirateData[pl:EntIndex()].LastPos=nil
	PirateData[pl:EntIndex()].KD = 0
	PirateData[pl:EntIndex()].LastSpawn = nil
	PirateData[pl:EntIndex()].parented = false
	PirateData[pl:EntIndex()].driving = false
//	pl:GetPhysicsObject():EnableDrag(false)
	if canSpawn then
		local bb=team.NumPlayers(TEAM_BLUE)
		local rr=team.NumPlayers(TEAM_RED)
		pl:Spectate(0)
		pl:UnSpectate()
		if bb==rr then
			pl:SetTeam(math.random(1,2))
		elseif bb>rr then
			pl:SetTeam(TEAM_RED)
		else
			pl:SetTeam(TEAM_BLUE)
		end
	else
		pl:SetTeam(TEAM_SPECTATE)
		pl:Spectate(5)
	end
end

//Give pistol and sabre
function GM:PlayerLoadout( pl )

//	GAMEMODE:PlayerSetModel( pl )
//	spawn = GAMEMODE:PlayerSelectSpawn( pl )
//	pl:SetPos(spawn:GetPos())
//	GAMEMODE:PlayerSpawn( pl )

	if pl:Team()==TEAM_SPECTATE then return end
	
	if pl:Team()==TEAM_BLUE||pl:Team()==TEAM_RED then
		pl:Give("weapon_ppistol")
		pl:Give("weapon_sabre")
		pl:GiveAmmo(2,"weapon_ppistol",false)
	end
end

//SetPlayerModel
function GM:PlayerSetModel( pl )
	if pl:Team()==TEAM_SPECTATE then return end
	if pl:Team()==TEAM_BLUE then
		pl:SetModel( "models/player/pirate/pirate_blue.mdl" )
	else
		pl:SetModel( "models/player/pirate/pirate_redd.mdl" )
	end
end

function pirate_eventPlayerSpawn( userid )
	if userid:Team() == TEAM_SPECTATE then
//		GM:ShowTeam( userid )
	end
end
hook.Add( "PlayerSpawn", pirate_eventPlayerSpawn )

//Called on team kill
function killedTooMuch( att )
	local kds = PirateData[attacker:EntIndex()].KD
	if kds==2 || kds==3 then
		att:PrintMessage(HUD_TALKCENTER, "You're team killing a lot! Stop it!")
	elseif kds==4 then
		att:PrintMessage(HUD_TALKCENTER, "One more team kill and you're outta here for a few min!")
	elseif kds>=5 then
		if !starting then
			game.ConsoleCommand( "banid 7.5 "..tostring( att:UserId() ).." kick" )
		end
	end
end

function pirate_eventPlayerKilled(killed, attacker, weapon)
	killed:AddDeaths(1)
	PirateData[killed:EntIndex()].Heal = false
	PirateData[killed:EntIndex()].parented = false
	PirateData[killed:EntIndex()].driving = false
//	killed:SetParent()
	//No points for team killers
	if killed:Team()!=attacker:Team() then
		team.AddScore(attacker:Team(), 1)
	else
		PirateData[attacker:EntIndex()].KD= PirateData[attacker:EntIndex()].KD+1
		killedTooMuch(attacker)
	end
end
hook.Add( "PlayerDeath", pirate_eventPlayerKilled )

//Player Death Hook
function plyDeath( ply, ent, att )
	if !canSpawn||sinking1||sinking2 then
		PirateData[v:EntIndex()].LastPos = ply:GetPos()+Vector(0,0,700)
		ply:SetTeam(TEAM_SPECTATE)
	end
end
hook.Add( "PlayerDeath", "changeTheirTeam", plyDeath )

////
//Main gamemode-related functions
////

//Simple function to print a message to the chat area for all players
function playerTalk( message )
	if message then
		local msg = tostring(message)
		for o,k in pairs(player.GetAll()) do
			k:PrintMessage( HUD_PRINTTALK, msg )
		end
	end
end

//Command to turn on or off leeches
function cc_leeches( ply, command, args )
	if(starting) then
		for k,v in pairs(ents.FindByName("leeches")) do
			if args[1] == "0" then
				v:Fire("Disable","",0)
			else
				v:Fire("Enable","",0)
			end
		end
	end
end
concommand.Add( "psw_leeches", cc_leeches )

/*//Command to start a new round
function cc_roundrestart( ply, command, args )
	if ply:IsAdmin() then
		spawnships()
		ships = false
		canSpawn = false
		for k,v in pairs(player.GetAll()) do
			v:SetTeam(TEAM_SPECTATE)
			v:Spectate(5)
		end
		timer.Simple(5, enableSpawning)
	end
end
concommand.Add( "psw_roundstart", cc_roundrestart )*/

//Spawns ships at map/round start
function GM:Think() //gamerulesThink()
	if !ships then
		spawnships()
		ships = true
	end
end

function checkSpec()
	if canSpawn then
		for k,v in pairs(player.GetAll()) do
//			if v:IsSpectating() then
				v:Spectate(0)
				v:UnSpectate()
//				v:ConCommand("kill")
//			end
		end
	end
end
timer.Create("GetOuttaSpec", 5, 0, checkSpec)

function GM:Initialize() //gamerulesStartMap()
	for k,v in pairs(player.GetAll()) do
		v:Freeze(false)
	end
	
//	WARNING, NEEDS TO BE EXECUTED ON BOTH CLIENT AND SERVER
//	team.SetUp(1, "Blue Pirates", Color(0,0,255,255) ) 
//	team.SetUp(2, "Red Pirates", Color(255,0,0,255) )
end

//SpawnShips
function spawnships()
	for k,v in pairs(ents.FindByName("spawnbutton")) do
		v:Fire("Press", "", 0)
	end
	
	sinking1=false
	sinking2=false
	disabled1=false
	disabled2=false
	starting=true

	for k,v in pairs(player.GetAll()) do
		local kds = PirateData[v:EntIndex()].KD
		PirateData[v:EntIndex()].KD = kds - 1
		if PirateData[v:EntIndex()].KD<0 then
			PirateData[v:EntIndex()].KD = 0
		end
	end
	timer.Simple(4,getshipparts)
	healtimer = timer.Simple(1,healer)
	timer.Simple(60,roundstart)
end

function roundstart()
	starting = false;
end

//Masts functions
function masts (activator, caller, entity)//(entity, caller, activator)//activator,caller,entity
	
//Red Ship
	if entity:GetName() == "s1pole" then
		if string.find(activator:GetClass(), "func_physbox") && ents.FindByName("ship1weldpolefront") then
			ents.GetByName( "ship1weldpolefront" ):Fire("Break", "", 0)
		end
	end
	
	if entit:GetName() == "s1polebreak" && !starting then
		ents.GetByName( "ship1polefront" ):Remove()
	end
	
	if entity:GetName() == "s1main" then
		if string.find(activator:GetClass(), "func_physbox") && ents.FindByName("ship1weldmastfront") then
			ents.GetByName( "ship1weldmastfront" ):Fire("Break", "", 0)
		end
	end
	
	if entity:GetName() == "s1mainbreak" && !starting then
		ents.GetByName( "ship1mastfront" ):Remove()
	end
	
	if entity:GetName() == "s1rear" then
		if string.find(activator:GetClass(), "func_physbox") && ents.FindByName("ship1weldmastback") then
			ents.GetByName( "ship1weldmastback" ):Fire("Break", "", 0)
		end
	end
	
	if entity:GetName() == "s1rearbreak" && !starting then
		ents.GetByName( "ship1mastback" ):Remove()
	end
	
//Blue Ship
	if entity:GetName() == "s2pole" then
		if string.find(activator:GetClass(), "func_physbox") && ents.FindByName("ship2weldpolefront") then
			ents.GetByName( "ship2weldpolefront" ):Fire("Break", "", 0)
		end
	end
	
	if entity:GetName() == "s2polebreak" && !starting then
		ents.GetByName( "ship2polefront" ):Remove()
	end
	
	if entity:GetName() == "s2main" then
		if string.find(activator:GetClass(), "func_physbox") && ents.FindByName("ship2weldmastfront") then
			ents.GetByName( "ship2weldmastfront" ):Fire("Break", "", 0)
		end
	end
	
	if entity:GetName() == "s2mainbreak" && !starting then
		ents.GetByName( "ship2mastfront" ):Remove()
	end
	
	if entity:GetName() == "s2rear" then
		if string.find(activator:GetClass(), "func_physbox") && ents.FindByName("ship2weldmastback") then
			ents.GetByName( "ship2weldmastback" ):Fire("Break", "", 0)
		end
	end
	
	if entity:GetName() == "s2rearbreak" && !starting then
		ents.GetByName( "ship2mastback" ):Remove()
	end
	
end
//hook.Add("EntityTakeDamage", "mastsFTW", masts)

//Functions such as cannons, stearing wheels, and healers
function shipfunctions (activator, arg, entity)//(entity, caller, activator) //activator, caller, entity

//Red Ship
	if entity:GetName() == "s1heal" then
		if activator:Team()==TEAM_RED then
			PirateData[activator:EntIndex()].Heal = true
		end
	end
	
	if entity:GetName() == "s1heal2" then
		if activator:Team()==TEAM_RED then
			PirateData[activator:EntIndex()].Heal = false
		end
	end
	
	if entity:GetName() == "ship1drivebutton"&&arg then
		if activator:Team() == TEAM_RED then
			activator:SetParent(ents.FindByName("ship1keel")[1])
			Msg("SettingParent\n")
			captain( activator, activator:Team(), 1 );
		end				
	end
	
	if entity:GetName() == "ship1drivebutton"&&!arg then
		if activator:Team() == TEAM_RED then
			activator:SetParent()
			captain( activator, activator:Team(), 2 );
		end
	end
	
	if entity:GetName() == "s1cannonfront" then
		if string.find ( activator:GetClass(), "func_tank" ) then
		s1frontuser:SelectWeapon("weapon_sabre");
//		_PlayerHolsterWeapon(s1frontuser);
		else
		s1frontuser = activator;
		end
	end
	
	if entity:GetName() == "s1cannonback" then
		if string.find ( activator:GetClass(), "func_tank" ) then
		s1backuser:SelectWeapon("weapon_sabre");
//		_PlayerHolsterWeapon(s1backuser);
		else
		s1backuser = activator;
		end
	end
	
//Blue Ship
	if entity:GetName() == "s2heal" then
		if activator:Team()==TEAM_BLUE then
			PirateData[activator:EntIndex()].Heal = true
		end
	end
	
	if entity:GetName() == "s2heal2" then
		if activator:Team()==TEAM_BLUE then
			PirateData[activator:EntIndex()].Heal = false
		end
	end
	
	if entity:GetName() == "ship2drivebutton"&&arg then
		if activator:Team() == TEAM_BLUE then
			activator:SetParent(ents.FindByName("ship1keel")[1])
			Msg("SettingParent\n")
			captain( activator, activator:Team(), 1 );
		end				
	end
	
	if entity:GetName() == "ship2drivebutton"&&!arg then
		if activator:Team() == TEAM_BLUE then
			activator:SetParent()
			captain( activator, activator:Team(), 2 );
		end
	end
	
	if entity:GetName() == "s2cannonfront" then
		if string.find ( activator:GetClass(), "func_tank" ) then
		s2frontuser:SelectWeapon("weapon_sabre");
//		_PlayerHolsterWeapon(s2frontuser);
		else
		s2frontuser = activator;
		end
	end
	
	if entity:GetName() == "s2cannonback" then
		if string.find ( activator:GetClass(), "func_tank" ) then
		s2backuser:SelectWeapon("weapon_sabre");
//		_PlayerHolsterWeapon(s2backuser);
		else
		s2backuser = activator;
		end
	end
end
//hook.Add("EntityTakeDamage", "shipFunctionsFTW", shipfunctions)

function healer()
/*	for k,v in pairs(player.GetAll()) do
		if PirateData[v:EntIndex()].Heal && v:Health() < 100  then
			v:SetHealth(v:Health() + (101 - v:Health())* .75)
		end				
	end*/
end

function findpartowner(ent)
	if string.find(ent:GetName(), "ship1") then
		return "red"
	end
	if string.find(ent:GetName(), "ship2") then
		return "blue"
	end
end

function getshipparts() --GETS ENTITY ID'S FROM ALL SHIP PARTS AND SET MASSES.
	--SHIP1 PARTS
	part3 = ents.GetByName("ship1bottom2left");
	part4 = ents.GetByName("ship1bottom2right");
	part5 = ents.GetByName("ship1bottom3left");
	part6 = ents.GetByName("ship1bottom3right");
	part8 = ents.GetByName("ship1bottom4right");
	part9 = ents.GetByName("ship1keel2");
	part11 = ents.GetByName("ship1sinker2");
	
	
	part13 = ents.GetByName("ship1polefront");
	part14 = ents.GetByName("ship1mastfront");
	part15 = ents.GetByName("ship1mastback");
	part16 = ents.GetByName("ship1door");
	part17 = ents.GetByName("ship1explosive");
	part18 = ents.GetByName("ship1keel");
	
	redparts = { part3, part4, part5, part6, part8, part9, part11 }
	
	part3:EnableDrag(false);
	part4:EnableDrag(false);
	part5:EnableDrag(false);
	part6:EnableDrag(false);
	part8:EnableDrag(false);
	part9:EnableDrag(false);
	part11:EnableDrag(false);
	
	part13:EnableDrag(false);
	part14:EnableDrag(false);
	part15:EnableDrag(false);
	part16:EnableDrag(false);
	part17:EnableDrag(false);
	part18:EnableDrag(false);
	
	
	
	part3:SetMass(40000);
	part4:SetMass(40000);
	part5:SetMass(40000);
	part6:SetMass(40000);
	part8:SetMass(35000);

	
	--SHIP2 PARTS
	s2part3 = ents.GetByName("ship2bottom2left");
	s2part4 = ents.GetByName("ship2bottom2right");
	s2part5 = ents.GetByName("ship2bottom3left");
	s2part6 = ents.GetByName("ship2bottom3right");
	s2part8 = ents.GetByName("ship2bottom4right");
	s2part9 = ents.GetByName("ship2keel2");
	s2part11 = ents.GetByName("ship2sinker2");
	
	blueparts = { s2part3, s2part4, s2part5, s2part6, s2part8, s2part9, s2part11 }
	
	s2part3:SetMass(40000);
	s2part4:SetMass(40000);
	s2part5:SetMass(40000);
	s2part6:SetMass(40000);
	s2part8:SetMass(35000);
end

function detectBreakage(ents, caller, attacker, amount)
	if attacker:IsPlayer() && string.find(ents:GetName(), "ship") then
//		Msg(attacker:Team())
		//if attacker:Team() == TEAM_RED && (string.find(ents:GetName(), "ship1")/*||string.find(ents:GetKeyValues().targetname, "ship1") */) then return false end
		//if attacker:Team() == TEAM_BLUE && (string.find(ents:GetName(), "ship2")/*||string.find(ents:GetKeyValues().targetname, "ship2")*/ ) then return false end
		if ents:GetClass() != "prop_physics_multiplayer"&&ents:GetClass() != "func_breakable" then
			return false
		end
	end
	local ent = ents:GetPhysicsObject()
	if string.find(ents:GetName(), "ship1explosive") then
		ship1barrel()
	elseif string.find(ents:GetName(), "ship2explosive") then
		ship2barrel()
	elseif string.find(ents:GetName(), "ship1") then
		if ent && ent:GetMass()>amount+5 then
			ent:SetMass(ent:GetMass()-amount)
		else
			ent:SetMass(5)
		end
		sink1(ents, amount)
	elseif string.find(ents:GetName(), "ship2") then
		if ent && ent:GetMass()>amount+5 then
			ent:SetMass(ent:GetMass()-amount)
		else
			ent:SetMass(5)
		end
		sink2(ents, amount)
	end
//	masts(attacker, caller, ents)
	
/*	if attacker:IsValid() && string.find(attacker:GetName(), "cannon") && string.find(attacker:GetName(), "ball") then
//		if !exploded[attacker:EntIndex()] then
//			exploded[attacker:EntIndex()]=1
//		end
//		if exploded[attacker:EntIndex()]<=2 then
			local pos = attacker:GetPos()
			local damage = 0.01
			for k,v in pairs(ents.FindInSphere(pos,75)) do
				if v:IsPlayer() then
					local health = v:Health()
					local dist = v:GetPos():Distance(pos)
					local tempDam=0
					if dist=0 then
						tempDam = damage
					else
					tempDam = damage/dist
					end
					v:SetHealth(health-teampDam)
				end
			end
			util.BlastDamage(attacker, attacker,pos,10,damage)
			local effectData = EffectData()
			effectData:SetStart(pos)
			effectData:SetOrigin(pos)
			effectData:SetScale(1)
			effectData:SetRadius(75)
			util.Effect("Explosion", effectData)
//			exploded[attacker:EntIndex()]=3
//		end
	attacker:Remove()
	end*/
end
hook.Add("EntityTakeDamage", "pirateBreaks", detectBreakage)

function ship1barrel()
	if !(disabled1) then
		playerTalk("RED PIRATE SHIP DISABLED")
		disabled1 = true
		for k,v in pairs(ents.FindByName("ship1backwardthruster")) do
			v:Remove()
		end
		
		ents.FindByName("ship1forwardthruster1")[1]:Remove()
		ents.FindByName("ship1forwardthruster")[1]:Remove()
		ents.FindByName("ship1rightthruster")[1]:Remove()
		ents.FindByName("ship1leftthruster")[1]:Remove()
	end
end

function ship2barrel()
	if !(disabled2) then
		playerTalk("BLUE PIRATE SHIP DISABLED")
		disabled2 = true
		for k,v in pairs(ents.FindByName("ship2backwardthruster")) do
			v:Remove()
		end
		
		ents.FindByName("ship2forwardthruster1")[1]:Remove()
		ents.FindByName("ship2forwardthruster")[1]:Remove()
		ents.FindByName("ship2rightthruster")[1]:Remove()
		ents.FindByName("ship2leftthruster")[1]:Remove()
	end
end

//Sink function, called when a piece of red ship breaks
function sink1()
//Msg("Sink func 1")
	if !sinking1 then
		if part8:GetMass()>6000 then
			part8:SetMass(part8:GetMass()-1000)
			if part11:GetMass()<34000 then
				part11:SetMass(part11:GetMass()+2000)
			end
		end
		
		if part3:GetMass()>3000 then
			part3:SetMass(part3:GetMass()-1000)
			part4:SetMass(part4:GetMass()-1000)
			part5:SetMass(part5:GetMass()-1000)
			part6:SetMass(part6:GetMass()-1000)
		else
			if !disabled1 then
				playerTalk("RED PIRATE SHIP DISABLED")
				disabled1 = true
			
				for k,v in pairs(ents.FindByName("ship1backwardthruster")) do
					v:Remove()
				end
				
				ents.FindByName("ship1forwardthruster1")[1]:Remove()
				ents.FindByName("ship1forwardthruster")[1]:Remove()
				ents.FindByName("ship1rightthruster")[1]:Remove()
				ents.FindByName("ship1leftthruster")[1]:Remove()
			end
			
			if part3:GetMass()>6000 then
				part8:SetMass(1000)
				part9:SetMass(25000)
				part3:SetMass(part3:GetMass() - 1000)
				part4:SetMass(part4:GetMass() - 1000)
				part5:SetMass(1000)
				part6:SetMass(1000)
				part11:SetMass(15000)
			else
				if !sinking2 then
					n1=35
					sinking1=true
					sinktimer = timer.Create("SinkTimer", 1, n1, CountDown)//timer.Simple(n1, CountDown)
					winner()
				end
			end
		end
	end
end

//Counts down red's death
function CountDown()
	if n1==30 then
		canSpawn=false
	end

	if n1 == 7 && sinking1 then
		timer.Stop(healtimer)//Not sure, maybe timer.Pause
		for k,v in pairs(player.GetAll()) do
//			if v:Team() == TEAM_RED then
//				v:Freeze(true)
				v:Spectate(OBS_MODE_ROAMING)
				v:SetTeam(TEAM_SPECTATE)//OBS_MODE_CHASE with v:SpectateEntity maybe good too
//			end
		end
		
		/*for k,v in pairs(player.GetAll()) do
			if v:IsConnected() then
				v:Spectate(OBS_MODE_ROAMING)//OBS_MODE_CHASE with v:SpectateEntity maybe good too
				//_PlayerHolsterWeapon(v);
			end
		end*/
	end
	
	if n1 == 5 && sinking1 then	
		spawnships();
	end
	
	if n1 == 1 then
		//Updates scores and respawbn players
		team.AddScore(TEAM_BLUE,30)
		
		//PlayerFreezeAll(false);
		timer.Remove("SinkTimer")
	canSpawn=true
		for k,v in pairs(player.GetAll()) do
//			if v:IsConnected() then
//				v:Freeze(false)
//				v:Spectate(OBS_MODE_NONE)
				v:UnSpectate()
				
				v:KillSilent( )
				v:Respawn() //Not sure really, this may be for non-player entities
			start(v);
//			end
		end	
	end	
	
	n1=n1-1;
	
	if (sinking1) then
		if part3:GetMass() > 400 then
			part3:SetMass(part3:GetMass()-200)
			part4:SetMass(part4:GetMass()-200)
		end	
		
		part8:SetMass(1000)
		if part11:GetMass() <= 40000 then		
			part5:SetMass(500);
			part6:SetMass(500);
			part11:SetMass(part11:GetMass()+1000); 
		end
		
		if part11:GetMass() > 40000 then
			part5:SetMass(1000)
			part6:SetMass(1000)
		
			if part9:GetMass() > 2000 then
				part9:SetMass(part9:GetMass()-1000)
			end
			
		else
			if part11:GetMass() > 49000 then
				part10:SetMass(35000)
				part9:SetMass(2000)
				part3:SetMass(1000)
				part4:SetMass(1000)
			end
		end
	end
end

//Blue ship sinking script
function sink2()
//Msg("Sink func 2")
	if !sinking2 then
		if s2part8:GetMass()>6000 then
			s2part8:SetMass(part8:GetMass()-1000)
			if s2part11:GetMass()<34000 then
				s2part11:SetMass(part11:GetMass()+2000)
			end
		end
		
		if s2part3:GetMass()>3000 then
			s2part3:SetMass(s2part3:GetMass()-1000)
			s2part4:SetMass(s2part4:GetMass()-1000)
			s2part5:SetMass(s2part5:GetMass()-1000)
			s2part6:SetMass(s2part6:GetMass()-1000)
		else
			if !disabled2 then
				playerTalk("BLUE PIRATE SHIP DISABLED")
				disabled2 = true
			
				for k,v in pairs(ents.FindByName("ship2backwardthruster")) do
					v:Remove()
				end
				
				ents.FindByName("ship2forwardthruster1")[1]:Remove()
				ents.FindByName("ship2forwardthruster")[1]:Remove()
				ents.FindByName("ship2rightthruster")[1]:Remove()
				ents.FindByName("ship2leftthruster")[1]:Remove()
				
			end
			
			if s2part3:GetMass()>6000 then
				s2part8:SetMass(1000)
				s2part9:SetMass(25000)
				s2part3:SetMass(s2part3:GetMass() - 1000)
				s2part4:SetMass(s2part4:GetMass() - 1000)
				s2part5:SetMass(1000)
				s2part6:SetMass(1000)
				s2part11:SetMass(15000)
			else
				if !sinking1 then
					n2=35
					sinking2=true
					sinktimer = timer.Create("SinkTimer2", 1, n2, CountDown2)//timer.Simple(n2, CountDown2)
					winner()
				end
			end
		end
	end
end

//Counts down blue's death
function CountDown2()

	if n1==30 then
		canSpawn=false
	end

	if n2 == 7 && sinking2 then
		timer.Stop(healtimer)//Not sure, maybe timer.Pause
		for k,v in pairs(player.GetAll()) do
//			if v:Team() == TEAM_BLUE then
//				v:Freeze(true)
				v:Spectate(OBS_MODE_ROAMING)//OBS_MODE_CHASE with v:SpectateEntity maybe good too
//			end
		end
//		_GModText_HideAll();
		
		/*for k,v in pairs(player.GetAll) do
			if v:IsConnected() then
				v:Spectate(OBS_MODE_ROAMING)//OBS_MODE_CHASE with v:SpectateEntity maybe good too
				//_PlayerHolsterWeapon(v);
			end
		end*/
	end
	
	if n2 == 5 && sinking2 then	
		spawnships();
	end
	
	if n2 == 1 then
		//Updates scores and respawbn players
		team.AddScore(TEAM_RED,30)
		
		//PlayerFreezeAll(false);
		timer.Remove("SinkTimer2")
		canSpawn=true
		for k,v in pairs(player.GetAll) do
//			if v:IsConnected() then
//				v:Freeze(false)
//				v:Spectate(OBS_MODE_NONE)
				v:UnSpectate()
				v:KillSilent( )
				v:Respawn() //Not sure really, this may be for non-player entities
			start(v);
//			end
		end	
	end			
	
	n2=n2-1;
	
	if (sinking2) then
		if s2part3:GetMass() > 400 then
			s2part3:SetMass(s2part3:GetMass()-200)
			s2part4:SetMass(s2part4:GetMass()-200)
		end	
		
		s2part8:SetMass(1000)
		if s2part11:GetMass() <= 40000 then		
			s2part5:SetMass(500);
			s2part6:SetMass(500);
			s2part11:SetMass(s2part11:GetMass()+1000); 
		end
		
		if s2part11:GetMass() > 40000 then
			s2part5:SetMass(1000)
			s2part6:SetMass(1000)
		
			if s2part9:GetMass() > 2000 then
				s2part9:SetMass(s2part9:GetMass()-1000)
			end
			
		else
			if s2part11:GetMass() > 49000 then
				s2part10:SetMass(35000)
				s2part9:SetMass(2000)
				s2part3:SetMass(1000)
				s2part4:SetMass(1000)
			end
		end
	end
end

function start(playerid)
	playerid:PrintMessage(HUD_PRINTCENTER,"Sink the enemy pirate ship!!!")
	//playerMessage("Sink the enemy pirate ship!!!")
end

//Select a captain
function captain(userid, team, id) //Run by steering wheel
	local colour = Color(0,0,0,255)
	local suppl = ""
	if team == TEAM_RED then
		colour = Color(255,30,30,255)
		local suppl = "Red"
	else
		colour = Color(30,30,255,255)
		local suppl = "Blue"
	end
	
	local text = ""
	
	if id==1 then
		text = suppl.." Captain: "..userid:Name()
	else
		text = "No "..suppl.." Captain."
	end
	
	for k,v in pairs(player.GetAll()) do
		if v:Team()==team then
			v:PrintMessage(HUD_PRINTCENTER, text)
		end
	end
end

//Anounce winner
function winner()
	local text=""
	
	if sinking1 then
		text="The Blue Pirates Win!"
	end
	
	if sinking2 then
		text="The Red Pirates Win!"
	end
	
	for k,v in pairs(player.GetAll()) do
		v:PrintMessage(HUD_PRINTCENTER, text)
	end
//	playerTalk(text)
end

function ents.GetByName( name )
	physent = ents.FindByName( name )[1]:GetPhysicsObject()
    return physent;
end